Mindex Metamethod
The __mindex
metamethod stands for 'method index'. It has a secondary priority to __index
and it's only invoked when the lookup is being performed by method invocation syntax. This is used to avoid compatibility issues regarding Pluto's default metatable for tables. For example:
pluto
local t = { "a", "b", "c" }print(t:concat()) --> abc
In this code, the following occurs:
concat
key is not directly present in the table, so__index
is queried.__index
returns nil.- Since
__index
returned nil and this lookup is being performed by method invocation syntax (:
),__mindex
is queried.
An example showing how __mindex is walked recursively so :insert still works with a custom __mindexpluto
local t = setmetatable({}, {__mindex = {function sum()local accum = 0for self as v doaccum += vendreturn accumend}})t:insert(1)t:insert(2)print(t.sum) --> nilprint(t:sum()) --> 3
An example of __index taking precedencepluto
local t = { 1, 2 }print(t:min()) --> 1t.min = 1print(t:min()) -- attempt to call a number value